package com.gxa.shop.servlet.product;

import com.alibaba.fastjson.JSONObject;

import com.gxa.shop.dao.product.ProductDao;
import com.gxa.shop.dao.product.impl.ProductDaoImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * com.gxa.shop.bean.servlet.product
 * User: zjy
 * Date: 2024/12/19 19:22
 * motto:   逆水行舟不进则退
 * Description:
 * Version: V1.0
 */
@WebServlet(name = "ProductUploadServlet",value = "/product/upload")
@MultipartConfig
public class ProductUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIR = "uploads"; // 文件存储目录
    private ProductDao productDao = new ProductDaoImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");

        // 获取上传的文件部分
        Part filePart = request.getPart("file");
        String fileName = extractFileName(filePart);

        // 从请求参数获取品牌ID（假设前端会传递此信息）
        String productId = request.getParameter("productId");

        // 检查是否有旧图片存在，并删除之
        String oldFilePath = productDao.getProductImageByProductId(productId);
        if (oldFilePath != null && !oldFilePath.isEmpty()) {
            File oldFile = new File(oldFilePath);
            if (oldFile.exists()) {
                oldFile.delete();
            }
        }
        // 设置保存路径
        String applicationPath = getServletContext().getRealPath("");
        String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

        // 创建文件夹（如果不存在）
        File uploadDir = new File(uploadFilePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 保存文件
        String filePath = uploadFilePath + File.separator + fileName;
        filePart.write(filePath);

        // 更新数据库中的图片路径
        productDao.updateProductImage(productId, filePath);

        // 返回 JSON 响应
        JSONObject jsonResponse = new JSONObject();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        jsonResponse.put("url", basePath + "/uploads/" + fileName);
        response.getWriter().write(jsonResponse.toJSONString());
    }

    private String extractFileName(Part part) {
        // 获取内容处置头部信息
        String contentDisp = part.getHeader("content-disposition");
        // 按照分号分割头部信息
        String[] items = contentDisp.split(";");
        // 遍历每个分割后的项
        for (String s : items) {
            // 检查项是否以 "filename" 开头
            if (s.trim().startsWith("filename")) {
                // 返回文件名，去掉前后的引号
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        // 如果没有找到文件名，返回空字符串
        return "";
    }
}